﻿using System.Collections.Generic;

namespace ThresholdAssistant.Redis
{
    /// <summary>
    ///redis工厂
    /// </summary>
    public class RedisClientFactory : IRedisClientFactory
    {

        /// <summary>
        /// 可用客户端字典列表
        /// </summary>
        private static Dictionary<string, IRedisClient> _clientDic = new Dictionary<string, IRedisClient>();

        /// <summary>
        /// 对象锁
        /// </summary>
        private static readonly object objlock = new object();

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="configs">连接客户端配置 key:连接key value:连接host</param>
        public RedisClientFactory(IDictionary<string, string> configs)
        {
            SetRedisClient(configs);
        }

        /// <summary>
        /// 获取客户端
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public IRedisClient GetRedisClient(string key)
        {
            return _clientDic[key];
        }

        /// <summary>
        /// 获取客户端实例化
        /// </summary>
        /// <returns></returns>
        private IRedisClient GetInstance(string connectionName)
        {
            return new CsRedisClientUtil(connectionName);
        }

        /// <summary>
        /// 设置Redis客户端
        /// </summary>
        /// <param name="configs"></param>
        private void SetRedisClient(IDictionary<string, string> configs)
        {
            if (configs == null)
            {
                return;
            }
            foreach (var config in configs)
            {
                if (!_clientDic.ContainsKey(config.Key))
                {
                    lock (objlock)
                    {
                        if (!_clientDic.ContainsKey(config.Key))
                        {
                            var client = GetInstance(config.Value);
                            if (client != null)
                            {
                                _clientDic.Add(config.Key, client);
                            }
                        }
                    }
                }
            }
        }
    }
}
